<?php

namespace addons\facrm\controller\facrm;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;


/**
 * 待办事项
 */
class Backlog extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'customer_id,name,mobile,telephone';
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);

    }

    /**
     * 待审批列表
     * @ApiParams(name="types", type="string", required=true, description="contract合同审批，receivables回款审批，invoice发票审批")
     */
    public function index()
    {
        $types = $this->request->request('types', "contract");
        $filter_w = [];
        if(!$model_str=\app\admin\model\facrm\Flow::getModelStr($types)){
            $this->error(__("审核类型有误"));
        }

        $this->model = model($model_str);
        //$filter_w[]=['exp','FIND_IN_SET('. $this->auth->id.',flow_admin_id)'];
        // $filter_w[]=['exp','FIND_IN_SET(2,flow_admin_id)'];
        $filter_w['check_status'] = ['in', [0, 1]];

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->where('', 'exp', 'FIND_IN_SET(' . $this->auth->id . ',flow_admin_id)')
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $this->model
            ->where($where)
            ->where($filter_w)
            ->where('', 'exp', 'FIND_IN_SET(' . $this->auth->id . ',flow_admin_id)');

        switch ($types) {
            case 'receivables':
                $this->model->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                    'contract' => function ($customer) {
                        $customer->field('id,name,number');
                    },
                ]);
                break;
            case "contract":
                $this->model->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'orderAdmin' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ]);
                break;
            case "invoice":
                $this->model->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'contract' => function ($user) {
                        $user->field('id,number,name');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ]);
                break;

        }


        $list = $this->model->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("rows" => $list);

        return $this->success('', $result);

    }

    /**
     * 审批
     * @ApiParams(name="types", type="string", required=true, description="contract合同审批，receivables回款审批")
     * @ApiParams(name="id", type="int", required=true, description="对应的待审批id")
     * @ApiParams(name="type", type="string", required=true, description="reject驳回，【审批的时候才需要】")
     * @ApiParams(name="next_admin_id", type="string", required=true, description="下个审批人,多个逗号隔开，如果是选择审批的话，需要结束就不要传【审批的时候才需要】")
     * @ApiParams(name="remark", type="string", required=true, description="备注，理由都是这个字段，【审批的时候才需要】")
     * @ApiBody ("get是获取审批信息，post是审批")
     */
    public function verify()
    {
        $types = $this->request->request('types', "contract");
        $ids = $this->request->request('id', "0",'intval');

        if(!$model_str=\app\admin\model\facrm\Flow::getModelStr($types)){
            $this->error(__("审核类型有误"));
        }

        $this->model = model($model_str);
        $Log = model('\app\admin\model\facrm\flow\Log');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->check_status == [0, 1]) {
            $this->error(__('不是待审核'));
        }

        if (!in_array($this->auth->id, explode(',', $row->flow_admin_id))) {
            $this->error(__('您没有权限审核'));
        }

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', $types)->where("status", 1)
            ->where('id', $row->flow_id)->find();

        if (!$flow_r) {
            $row->check_status=3;
            $row->flow_id=0;
            $row->flow_admin_id=$row->check_admin_id="";//已审批的人清空
            $row->save();
            $this->error(__('审核流程不存在,已经直接驳回！'));
        }

        $flow_r->step = $flow_r->step()->where('id', '>', $row->step_id)->select();
        if ($this->request->isPost()) {
            $type = $this->request->post("type");
            $next_admin_id = $this->request->post("next_admin_id");
            $log_data = array();
            $log_data['flow_id'] = $row->flow_id;
            $log_data['types'] = $types;
            $log_data['types_id'] = $row->id;
            $log_data['admin_id'] = $this->auth->id;
            $log_data['nickname'] = $this->auth->nickname;
            $log_data['remark'] = $this->request->post("remark", '');
            $log_data['is_end'] = 0;
            $log_data['status'] = 0;//未通过
            Db::startTrans();
            try {
                //驳回
                if ($type == 'reject') {
                    $row->check_status = 3;
                    $row->check_admin_id = "";//已审批的人清空
                } else {
                    //通过
                    //判断是否还有下一级审批人
                    if ($flow_r->config == 1 && $flow_r->step) {
                        $flow_admin_id = $flow_r->step[0]['admin_ids'];
                        if ($flow_r->step[0]['type'] == 1) {
                            //上级领导审批
                            $parentIds = $this->auth->getParentAdminIds($this->auth->id);
                            $flow_admin_id = $parentIds ? join(',', $parentIds) : $this->auth->id;//如果没有父类就是最高级的，同时也要审核一下
                        }else if ($flow_r->step[0]['type']==3){
                            //指定部门
                            $auth=new  \addons\facrm\library\Auth();
                            $groupIds=$auth->getGroupsAdminIds($flow_r->step[0]['admin_ids']);
                            $flow_admin_id=$groupIds?join(',',$groupIds):$this->auth->id;//如部门人自己也要审核一下

                        }
                        $row->check_status = 1;
                        $row->flow_admin_id = $flow_admin_id;
                        $row->step_id = $flow_r->step[0]['id'];
                    } elseif ($flow_r->config == 0 && $next_admin_id) {
                        $row->check_status = 1;
                        $row->flow_admin_id = $next_admin_id;
                    } else {
                        $row->flow_admin_id = "";
                        $row->check_status = 2;
                        $log_data['is_end'] = 1;
                    }
                    $row->check_admin_id .= $row->check_admin_id ? ',' . $this->auth->id : $this->auth->id;
                    $log_data['status'] = 1;//通过
                }
                $row->save();
                //记录审核日志
                $Log->save($log_data);
                hook("facrm_flow_verify", array_merge($log_data, ['id' => $Log->id, 'flow' => $flow_r]));
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $return_data=array();
        //获取审核日志
        $log_list = $Log->where('flow_id', $row->flow_id)->where('types_id', $row->id)->select();
        $return_data['row']=$row;
        $return_data['flow']=$flow_r;
        $return_data['log_list']=$log_list;

        switch ($types) {
            case "contract":
                $row->product;
                break;
        }
        $this->success('',$return_data);
    }

}
